package com.ginmeta.common.base;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.ginmeta.common.utils.ServletUtils;
import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * 分页数据
 * @author GinMeta
 */
@Data
@AllArgsConstructor
public class PageModel {
    /**
     * 当前记录起始索引
     */
    private Integer pageNumber;

    /**
     * 每页显示记录数
     */
    private Integer pageSize;

    /**
     * 排序列
     */
    private String orderByColumn;

    /**
     * 排序的方向desc或者asc
     */
    private String isAsc = "asc";

    public static final String PAGE_NUMBER = "pageNumber";

    public static final String PAGE_SIZE = "pageSize";

    public static final String ORDER_BY_COLUMN = "orderByColumn";

    public static final String IS_ASC = "isAsc";

    public String getOrderBy() {
        if (StrUtil.isEmpty(orderByColumn)) {
            return "";
        }
        return StrUtil.toUnderlineCase(orderByColumn) + " " + isAsc;
    }

    public void setIsAsc(String isAsc) {
        if (StrUtil.isNotEmpty(isAsc)) {
            // 兼容前端排序类型
            if ("ascending".equals(isAsc)) {
                isAsc = "asc";
            } else if ("descending".equals(isAsc)) {
                isAsc = "desc";
            }
            this.isAsc = isAsc;
        }
    }

    public PageModel() {
        this.pageNumber = Convert.toInt(ServletUtils.getParameter(PAGE_NUMBER), 1);
        this.pageSize = Convert.toInt(ServletUtils.getParameter(PAGE_SIZE), 10);
        this.orderByColumn = ServletUtils.getParameter(ORDER_BY_COLUMN);
        this.isAsc = ServletUtils.getParameter(IS_ASC);
    }

}
